import time
import json

import webapp2
from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, syndic, contact, person, company

from wtforms.ext.appengine.db import model_form

from common import functions

from BaseHandler import BaseHandler

class Contacts(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Contacts, self).__init__(*args, **kwargs)
        self.fields = {
                       'type': _('Type'), 'default_phone': _('Primary phone number'), 'default_email': _('Email'),
                       'address': _('Address'), 'wwwsite': _('Site'), 'syndic': _('Syndic'), 'pname': _('Name'),
                       'first_name': _('First name'), 'last_name': _('Last name'), 'cell_phone': _('Cell phone'),
                       'home_phone': _('Home phone'), 'office_phone': _('Office phone'), 'birthday': _('Birthday'),
                       'name': _('Company name'), 'fax_number': _('Fax'), 'phone': _('Phone')
                       }

    def get(self, imm_id, command, c_id=None):
        if not command or command == 'list':
            self.op_list(imm_id)
        if command == 'add_person':
            self.op_add(imm_id, 'person')
        if command == 'add_company':
            self.op_add(imm_id, 'company')
        if command == 'edit':
            self.op_edit(imm_id, c_id)
        if command == 'list_json':
            self.op_list_json(imm_id)
    
    def post(self, imm_id, command=None, c_id=None):
        if command == 'add_person':
            self.op_add(imm_id, 'person')
        if command == 'add_company':
            self.op_add(imm_id, 'company')
        if command == 'edit':
            self.op_edit(imm_id, c_id)
    
    def op_list(self, imm_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Contacts. %s' % imm.name),
                           'header': _('%s. Contacts.' % imm.name),
                           'app_user': au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'contacts',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/contact_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, imm_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        syn = imm.syndic
        contacts = syn.syndic_contacts.run()
        co = []
        for c in contacts:
            co.append([c.class_name(), unicode(c), unicode(c.address), c.wwwsite, c.default_phone, c.default_email, str(c.key().id())])
        ret = {}
        ret['aaData'] = co
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, imm_id, who):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        if who == 'person':
            PersonForm = model_form(person, only=['first_name','last_name','default_phone','default_email','address','wwwsite','cell_phone','home_phone','office_phone','birthday'])
        else:
            CompanyForm = model_form(company, only=['name','default_phone','default_email','address','wwwsite','fax','phone'])
            
        if self.request.method == 'GET':
            if who == 'person':
                form = PersonForm()
            else:
                form = CompanyForm()
            
        if self.request.method == 'POST':
            if who == 'person':
                form = PersonForm(self.request.POST)
            else:
                form = CompanyForm(self.request.POST)
            
            if form.validate():
                if who == 'person':
                    new_contact = person(syndic = imm.syndic, first_name = 'a', last_name = 'b')
                    form.populate_obj(new_contact)
                    new_contact.put()
                    ok_message = _('Person was added.')
                else:
                    new_contact = company(syndic = imm.syndic, name = 'great company')
                    form.populate_obj(new_contact)
                    new_contact.put()
                    ok_message = _('Company was added.')
                while not new_contact.is_saved():
                    time.sleep(2)
                
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, imm_id, c_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        edit_contact = contact.get_by_id(int(c_id))
        if not edit_contact:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        if edit_contact.class_name() == 'person':
            PersonForm = model_form(person, only=['first_name','last_name','default_phone','default_email','address','wwwsite','cell_phone','home_phone','office_phone','birthday'])
        else:
            CompanyForm = model_form(company, only=['name','default_phone','default_email','address','wwwsite','fax','phone'])
        
        if self.request.method == 'GET':
            if edit_contact.class_name() == 'person':
                form = PersonForm(obj=edit_contact)
            else:
                form = CompanyForm(obj=edit_contact)
            
        if self.request.method == 'POST':
            if edit_contact.class_name() == 'person':
                form = PersonForm(self.request.POST)
            else:
                form = CompanyForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(edit_contact)
                edit_contact.put()
                ok_message = _('Contact was updated.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))

class ContactDetail(BaseHandler):
    def show(self, s_id, c_id):
        au = functions.GetAPNETUser()
        if not au:
            self.redirect('/')
    
        syn = syndic.get_by_id(int(s_id))
        if not syn:
            self.redirect('/ams/syndic/')
            return
        
        new_contact = contact.get_by_id(int(c_id))
        if not new_contact:
            self.redirect(users.create_login_url('/ams/syndic/'))
            return
        
        if new_contact.class_name() == 'person':
            show_contact = person.get_by_id(new_contact.key().id())
            DetailForm = model_form(person, exclude=['syndic'])
        else:
            show_contact = company.get_by_id(new_contact.key().id())
            DetailForm = model_form(company, exclude=['syndic'])
        
        form = DetailForm(obj=show_contact)
        
        template_values = {
                           'form': form,
                           'ok_message': ''
                           }
        
        template = self.jinja2.get_template('templates/base_detail.html')
        self.response.out.write(template.render(template_values))
    
    def get(self, s_id, c_id):
        self.show(s_id, c_id)
